package com.voice.server.channel.handle.impl;

import com.voice.core.entity.HttpHeader;
import com.voice.core.connection.Connection;
import com.voice.core.connection.ConnectionStatus;
import com.voice.core.connection.impl.SocketChannelConnectionImpl;
import com.voice.server.connection.ConnectionInvoke;
import com.voice.server.connection.DeviceControllerConnection;
import com.voice.server.connection.map.DeviceControllerConnectionMap;
import com.voice.server.observer.impl.CmdObservable;
import com.voice.server.publish.PublishHandler;
import com.wangjiacai.utils.web.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;


@Slf4j
@Component("/device/controller/echo/success")
public class DeviceControllerStreamListener extends AbstractStreamListenerHandler<DeviceControllerConnection> {

    @Autowired
    private DeviceControllerConnectionMap connectionMap;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ConnectionInvoke connectionInvoke;
    @Autowired
    private Map<String, PublishHandler> publishHandlerMap;

    @Override
    public DeviceControllerConnection conversionTo(HttpHeader requestHeader, Connection connection) throws Exception {
        String deviceKey = requestHeader.get("deviceKey", String.class);
        String userId=requestHeader.get("userId",String.class);
        DeviceControllerConnection deviceConnection=new DeviceControllerConnection((SocketChannelConnectionImpl) connection,userId, deviceKey);
        return deviceConnection;
    }

    @Override
    public void handle(HttpHeader requestHeader, Connection connection) throws Exception {
        DeviceControllerConnection  t = conversionTo(requestHeader,connection);
        t.setDefaultStreamListener(this);
        t.setConnectionListener(this);
        t.setStatus(ConnectionStatus.AUTHORIZED);
        Integer pushType=redisService.hashGet(CmdObservable.hashKey,t.getDeviceKey(),Integer.class);
        if(pushType!=null) connectionInvoke.sendServerMessageToDevice(t.getUserId(),t.getDeviceKey(),pushType);
    }

    @Override
    public void onStatusChange(ConnectionStatus status, DeviceControllerConnection connection) {
        switch (status) {
            case CLOSED:
                log.info("DeviceControllerConnection:{} 断开",connection);
                connectionMap.remove(connection.getDeviceKey());
                break;
            case AUTHORIZED:
                log.info("DeviceControllerConnection:{} 连接",connection);
                connectionMap.put(connection.getDeviceKey(),connection);
                break;
        }
    }


    @Override
    public PublishHandler getPublishHandler(String path) {
        return publishHandlerMap.get(path);
    }
}
